//
//  CommentView.m
//  XiaoHongShu
//
//  Created by Jason on 2022/7/29.
//

#import "CommentView.h"
#import "CommentHeaderView.h"
#import "ReplyCell.h"
#import "CommentListModel.h"
#import "DataModel.h"
#import "CommentHeaderViewFrame.h"
#import "CommentCellFrame.h"
#import "UIColor+DarkAndLightColor.h"
#import "CommentDataModel.h"


@interface CommentView ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) NSMutableArray *commentListArr;;

@property (nonatomic, strong) UIView *commentCountView;

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIView *topLineView;

@property (nonatomic, strong) UIView *bottomAddCommentView;

@property (nonatomic, assign) CGFloat headerViewHeight;

//@property (nonatomic, strong) NSMutableArray *commentArr;
//
//@property (nonatomic, strong) NSMutableArray *subCommentArr;

@property (nonatomic, strong) NSMutableArray<CommentDataModel *> *commentDataArr;

//加载子评论数量
@property (nonatomic, assign) NSInteger subCommentSize;

//子评论列表上拉加载的page
@property (nonatomic, assign) NSInteger pageNum;

//评论输入框
@property (nonatomic, strong) UITextField *commentTF;

//表情包按钮
@property (nonatomic, strong) UIButton *emojiBtn;

//@ 按钮
@property (nonatomic, strong) UIButton *atBtn;

//输入框文本发送按钮
@property (nonatomic, strong) UIButton *sendTextBtn;

@property (nonatomic, strong) NSMutableArray *excludeCommentIdsmArr;

@property (nonatomic, copy) NSString *commentText;

@property (nonatomic, strong) NSMutableDictionary *commentTextDict;

@property (nonatomic, strong) NSIndexPath *cellIndexPath;

@property (nonatomic, assign) BOOL isHeaderView;

@property (nonatomic, strong) NSMutableDictionary *selectUserMdict;

@end

@implementation CommentView

-(NSMutableDictionary *)commentTextDict {
    if (!_commentTextDict) {
        _commentTextDict = [NSMutableDictionary dictionary];
    }
    return _commentTextDict;
}

-(NSMutableDictionary *)selectUserMdict {
    if (!_selectUserMdict) {
        _selectUserMdict = [NSMutableDictionary dictionary];
    }
    return _selectUserMdict;
}

-(NSMutableArray *)excludeCommentIdsmArr {
    if (!_excludeCommentIdsmArr) {
        _excludeCommentIdsmArr = [NSMutableArray array];
    }
    return _excludeCommentIdsmArr;
}

-(NSMutableArray<CommentDataModel *> *)commentDataArr {
    if (!_commentDataArr) {
        _commentDataArr = [NSMutableArray array];
    }
    return _commentDataArr;
}

- (UIView *)commentCountView {
    if (!_commentCountView) {
        _commentCountView = [[UIView alloc]init];
        if (@available(iOS 13.0, *)) {
            _commentCountView.backgroundColor = [UIColor colorWithLight:kWhiteColor dark:kBlackColor];
        } else {
            _commentCountView.backgroundColor = kWhiteColor;
        }
    }
    return _commentCountView;
}

-(UILabel *)commentCountLabel {
    if (!_commentCountLabel) {
        _commentCountLabel = [[UILabel alloc]init];
      //  _commentCountLabel.text = [NSString stringWithFormat:@"共 %ld 条评论", self.commentCount];
        _commentCountLabel.textAlignment = NSTextAlignmentCenter;
        _commentCountLabel.font = kBoldFont(14);
        if (@available(iOS 13.0, *)) {
            _commentCountLabel.textColor = [UIColor labelColor];
        } else {
            _commentCountLabel.textColor = kBlackColor;
        }
    }
    return _commentCountLabel;
}

-(UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [[UIButton alloc]init];
        [_backBtn setTitle:@"X" forState:UIControlStateNormal];
        if (@available(iOS 13.0, *)) {
            [_backBtn setTitleColor:[UIColor labelColor] forState:UIControlStateNormal];
        } else {
            [_backBtn setTitleColor:[UIColor lightTextColor] forState:UIControlStateNormal];
        }
        [_backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

-(UIView *)topLineView {
    if (!_topLineView) {
        _topLineView = [[UIView alloc]init];
        _topLineView.backgroundColor = kRGBHex(0xeeeeee);
    }
    return _topLineView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //取消tableView的分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = kWhiteColor;
        _tableView.showsVerticalScrollIndicator = NO;
        //给tableView 添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(tableViewLongPress:)];
        [_tableView addGestureRecognizer:longPress];
    }
    return _tableView;
}

-(UIView *)bottomAddCommentView {
    if (!_bottomAddCommentView) {
        _bottomAddCommentView = [[UIView alloc]init];
        _bottomAddCommentView.backgroundColor = kWhiteColor;
    }
    return _bottomAddCommentView;
}

-(UITextField *)commentTF {
    if (!_commentTF) {
        _commentTF = [[UITextField alloc]init];
        _commentTF.placeholder = @"喜欢就给个评论支持一下 ~";
        _commentTF.backgroundColor = kRGBHex(0xeeeeee);
        //_commentTF.borderStyle = UITextBorderStyleRoundedRect;
        _commentTF.layer.cornerRadius = 18;
        _commentTF.layer.masksToBounds = YES;
        //设置输入框右移(给输入框的左侧设置一个占位view)
        UIView *commentLeftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, _commentTF.frame.size.height)];
        _commentTF.leftViewMode = UITextFieldViewModeAlways;
        _commentTF.leftView = commentLeftView;
        //设置 placeholder 文本
        NSAttributedString *attr = [[NSAttributedString alloc]initWithString:_commentTF.placeholder attributes:@{NSFontAttributeName: kFont(12), NSForegroundColorAttributeName: kDarkGrayColor}];
        _commentTF.attributedPlaceholder = attr;
        //设置输入框光标颜色
        _commentTF.tintColor = kRGBColor(49, 125, 246);
        //设置键盘的类型
        _commentTF.returnKeyType = UIReturnKeySend;
        _commentTF.delegate = self;
    }
    return _commentTF;
}

-(UIButton *)emojiBtn {
    if (!_emojiBtn) {
        _emojiBtn = [[UIButton alloc]init];
        [_emojiBtn setImage:kImageName(@"笑脸") forState:UIControlStateNormal];
        [_emojiBtn addTarget:self action:@selector(emojiBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _emojiBtn;
}

-(UIButton *)atBtn {
    if (!_atBtn) {
        _atBtn = [[UIButton alloc]init];
       // _atBtn.backgroundColor = kYellowColor;
        [_atBtn setImage:kImageName(@"符号-@") forState:UIControlStateNormal];
        [_atBtn addTarget:self action:@selector(atBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _atBtn;
}

- (UIButton *)sendTextBtn {
    if (!_sendTextBtn) {
        _sendTextBtn = [[UIButton alloc]init];
        [_sendTextBtn setTitle:@"发送" forState:UIControlStateNormal];
        _sendTextBtn.titleLabel.font = kBoldFont(17);
        _sendTextBtn.backgroundColor = kRGBColor(49, 125, 246);
        _sendTextBtn.layer.cornerRadius = 18;
        _sendTextBtn.layer.masksToBounds = YES;
        _sendTextBtn.hidden = YES;
    }
    return _sendTextBtn;
}

#pragma mark - 评论返回按钮的点击事件
- (void)backBtnClick {
    //获取commentView 的终极父类 _bgView
    self.superview.superview.transform = CGAffineTransformMakeTranslation(0, kSPScreenHeight);
}

#pragma mark - initWithFrame:
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        //监听键盘的位置发生改变
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        NSLog(@"1---center = %@",center);
        //添加监听
        [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
        
    }
    return self;
}

#pragma mark - 监听键盘的位置变化
- (void)keyboardWillChangeFrame:(NSNotification *)noteInfo {
    NSLog(@"noteInfo = %@",noteInfo);
    NSLog(@"通知的名称： %@",noteInfo.name);
    NSLog(@"发送监听的对象：%@",noteInfo.object);
    NSLog(@"通知的内容：%@",noteInfo.userInfo);
    CGRect rectEnd = [noteInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = rectEnd.origin.y;
    CGFloat tranformValue = keyboardY - kSPScreenHeight;
    if (tranformValue == 0) {
        self.coverView.hidden = YES;
    } else {
        self.coverView.hidden = NO;
    }
    [UIView animateWithDuration:0.25 animations:^{
        //重置遮罩view 的frame
        self.coverView.frame = CGRectMake(0, 0, kSPScreenWidth, keyboardY - CGRectGetHeight(self.bottomAddCommentView.frame));
        self.bottomAddCommentView.transform = CGAffineTransformMakeTranslation(0, tranformValue);
    }];
}

#pragma mark - emojiBtnClick
- (void)emojiBtnClick {
    NSLog(@"点击了 - emojiBtn");
}

#pragma mark - atBtnClick
- (void)atBtnClick {
    NSLog(@"atBtnClick");
}


-(void)dealloc {
    NSLog(@"CommentView - dealloc");
    //在这个CommentView 被释放的时候移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 获取评论列表
- (void)loadRequestWithRefreshType:(MJRefreshType )refreshType currentPage:(NSInteger)currentPage {
    NSLog(@"1----excludeCommentIdsmArr = %@",self.excludeCommentIdsmArr);
    NSLog(@"----noteId = %ld",self.noteId);
    _subCommentSize = 1;
    NSDictionary *paramDict = @{
        @"noteId" : @(self.noteId),
        @"subCommentSize" : @(_subCommentSize),
        @"excludeCommentIds": self.excludeCommentIdsmArr,
        @"current" : @(currentPage),
        @"size" : @(10)
    };
    [[HttpRequest shareInstance] post: kNotesListComment parameters:paramDict success:^(NSURLSessionDataTask * _Nonnull task, HttpResponseModel * _Nullable responseModel) {
        NSLog(@"评论 list - responseModel = %@", responseModel);
        if (responseModel.code.integerValue == 0) {
            NSLog(@"评论列表显示成功");
            DataModel *dataModel = [DataModel yy_modelWithDictionary:responseModel.data];
            NSArray<BaseModel *> *listArr = [CommentListModel arrayFromJSONArray: dataModel.records];
            NSLog(@"listArr = %@",listArr);
            if (refreshType == MJRefreshTypePullUp) {
                if (listArr != nil && listArr.count > 0) {
                    [self getCommentListWithCommentArr:listArr];
                    [self.tableView.mj_footer endRefreshing];
                } else {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                [self getCommentListWithCommentArr:listArr];
            }
            [self.tableView reloadData];
        }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"加载失败 - error = %@", error);
            [PRTools showProgressHUDWithError:@"加载失败..." afterDelay:1];
        }];
}


- (void)getCommentListWithCommentArr:(NSArray *)commentArr {
    for (CommentListModel *model in commentArr) {
        CommentHeaderViewFrame *headerViewFrame = [[CommentHeaderViewFrame alloc]init];
        headerViewFrame.commentModel = model;
       
        CommentDataModel *commentDataModel = [[CommentDataModel alloc]init];
        commentDataModel.headerViewFrame = headerViewFrame;
        
        //获取当前遍历的这一组的子评论
        NSArray *subCommentListArr = [CommentListModel arrayFromJSONArray:model.subComments];
        
        NSMutableArray *subCommentArr = [NSMutableArray array];
        
        for (CommentListModel * subCommentModel in subCommentListArr) {
            CommentCellFrame *cellFrame = [[CommentCellFrame alloc]init];
            cellFrame.commentListModel = subCommentModel;
            [subCommentArr addObject:cellFrame];
        }
        commentDataModel.cellFrameArr = subCommentArr;
        [self.commentDataArr addObject:commentDataModel];
    }
    NSLog(@"commentDataArr = %@", self.commentDataArr);
}

- (void)setupUI {
    [self addSubview:self.commentCountView];
    [self.commentCountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    [self.commentCountView addSubview:self.commentCountLabel];
    [self.commentCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(self.commentCountView);
        make.centerX.mas_equalTo(self.commentCountView);
    }];
    
    [self.commentCountView addSubview:self.backBtn];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.mas_equalTo(self.commentCountView);
        make.width.height.mas_equalTo(44);
    }];
    
    [self.commentCountView addSubview:self.topLineView];
    [self.topLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.bottom.mas_equalTo(self.commentCountView);
        make.height.mas_equalTo(1);
        
    }];
    
    [self addSubview:self.tableView];
    CGFloat tabbarH = [UIDevice vg_tabBarFullHeight];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.commentCountView.mas_bottom);
        make.left.right.mas_equalTo(self);
        make.bottom.mas_equalTo(self).mas_offset(-tabbarH);
    }];
    
    [self addSubview:self.bottomAddCommentView];
    [self.bottomAddCommentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tableView.mas_bottom).mas_offset(2);
        make.left.right.mas_equalTo(self);
        make.bottom.mas_equalTo(self);
    }];
    
    [self.bottomAddCommentView addSubview:self.commentTF];
    [self.commentTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomAddCommentView).mas_offset(10);
        make.left.mas_equalTo(self).mas_offset(10);
        make.right.mas_equalTo(self).mas_offset(-10);
        make.height.mas_equalTo(36);
    }];
    
    [self.commentTF addSubview:self.emojiBtn];
    [self.emojiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.commentTF).mas_offset(-15);
        make.width.height.mas_equalTo(18);
        make.centerY.mas_equalTo(self.commentTF);
    }];
    
    [self.commentTF addSubview:self.atBtn];
    [self.atBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.emojiBtn.mas_left).mas_offset(-10);
        make.width.height.mas_equalTo(18);
        make.centerY.mas_equalTo(self.commentTF);
    }];
    
    [self.bottomAddCommentView addSubview:self.sendTextBtn];
    [self.sendTextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.bottomAddCommentView).mas_offset(-5);
        make.width.mas_equalTo(60);
        make.centerY.height.mas_equalTo(self.commentTF);
    }];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.commentDataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.commentDataArr[section] cellFrameArr] count];
}

//这个数据源方法一直都会执行（一开始运行进来就执行了这个方法，所以height为0）
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    //获取模型数据
    CommentHeaderViewFrame *headerViewFrame = [self.commentDataArr[section] headerViewFrame];
   // NSLog(@"headerViewHeight = %lf",headerViewFrame.headerViewHeight);
    return headerViewFrame.headerViewHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CommentHeaderView *headerView = [CommentHeaderView CommentHeaderViewWithTableView:tableView];
    headerView.headerViewFrame = [self.commentDataArr[section] headerViewFrame];
    //获取headerView的tag
    headerView.tag = section;
    //给headerView 添加轻点手势
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerViewTap:)];
    headerView.userInteractionEnabled = YES;
    [headerView addGestureRecognizer:tapGest];
    //给headerView 添加长按手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(headerViewLongPress:)];
    [headerView addGestureRecognizer:longPress];
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    //获取组的模型
    CommentHeaderViewFrame *headerViewFrame = [self.commentDataArr[section] headerViewFrame];
    NSInteger subCommentCount = headerViewFrame.commentModel.subCommentCount;
    //NSLog(@"获取组的模型 - subCommentCount = %ld",subCommentCount);
    if (subCommentCount > [[self.commentDataArr[section] cellFrameArr] count]) {
        return 34;
    } else {
        return 1;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    self.pageNum = 0;
    UIView *footerView = [[UIView alloc]init];
    footerView.backgroundColor = kClearColor;
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [footerView addSubview:lineView];
    UIButton *footerBtn = [[UIButton alloc]init];
    footerBtn.backgroundColor = kWhiteColor;
    [footerBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    footerBtn.titleLabel.font = kFont(12);
    footerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    footerBtn.tag = section;
    //获取组的模型
    CommentHeaderViewFrame *headerViewFrame = [self.commentDataArr[section] headerViewFrame];
    NSInteger subCommentCount = headerViewFrame.commentModel.subCommentCount;
    //展开的子评论数量(总的子评论数量 - 加载子评论数量)
    NSInteger expandSubcount = 0;
    //当前加载的子评论的数量
    NSInteger currentSubCommentCount = [[self.commentDataArr[section] cellFrameArr] count];
    if (subCommentCount > currentSubCommentCount) {
        expandSubcount = subCommentCount - currentSubCommentCount;
        [footerBtn setTitle:[NSString stringWithFormat:@"展开 %ld 条回复", expandSubcount] forState:UIControlStateNormal];
        lineView.frame = CGRectMake(45, 34 - 1, tableView.frame.size.width - 45, 1);
        footerBtn.frame = CGRectMake(70, 0, tableView.frame.size.width - 70, 34 - 1);
    } else {
        lineView.frame = CGRectMake(45, 0, tableView.frame.size.width - 45, 1);
        footerBtn.frame = CGRectMake(0, 0, 0, 0);
    }
    [footerBtn addTarget:self action:@selector(footerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:footerBtn];
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentCellFrame *cellFrame = [self.commentDataArr[indexPath.section] cellFrameArr][indexPath.row];
    return cellFrame.cellHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ReplyCell *cell = [ReplyCell replyCellWithTableView:tableView];
    cell.commentCellFrame = [self.commentDataArr[indexPath.section] cellFrameArr][indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - 获取子评论接口
- (void)loadRequestWithSubCommentWithTopCommentId:(NSInteger)topCommentId section:(NSInteger)section subComentId:(NSInteger)subCommentId currentPage:(NSInteger)currentPage {
    [self.excludeCommentIdsmArr addObject:@(subCommentId)];
    NSDictionary *paramDict = @{
        @"topCommentId": @(topCommentId),
        @"excludeCommentIds": self.excludeCommentIdsmArr,
        @"current": @(currentPage),   //点击展开按钮翻页（当前页数 +1）
        @"size": @(10)
    };
    [[HttpRequest shareInstance] post:kNotesSubListComment parameters:paramDict success:^(NSURLSessionDataTask * _Nonnull task, HttpResponseModel * _Nullable responseModel) {
        NSLog(@"获取子评论接口 - %@", responseModel);
        if (responseModel.code.integerValue == 0) {
           // NSInteger lastCount = [self.subCommentArr[section] count];
            NSLog(@"获取子评论接口成功");
            DataModel *dataModel = [DataModel yy_modelWithDictionary:responseModel.data];
            NSArray *subListArr = [CommentListModel arrayFromJSONArray:dataModel.records];
            NSLog(@"subListArr = %@",subListArr);
            [self getSubCommentListArr:subListArr section:section];
            [self.tableView reloadData];
           // [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:lastCount inSection:section] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"加载失败 - error = %@", error);
            [PRTools showProgressHUDWithError:@"加载失败..." afterDelay:1];
        }];
}

- (void)getSubCommentListArr:(NSArray *)subCommentArr section:(NSInteger)section {
    for (CommentListModel *subCommentModel in subCommentArr) {
        CommentCellFrame *cellFrame = [[CommentCellFrame alloc]init];
        cellFrame.commentListModel = subCommentModel;
        [[self.commentDataArr[section] cellFrameArr] addObject:cellFrame];
    }
    NSLog(@"---commentDataArr - %@",self.commentDataArr);
}

#pragma mark - footerBtnClick
- (void)footerBtnClick:(UIButton *)sender {
    NSLog(@"点击展开子评论按钮");
    //获取顶级评论ID
    CommentHeaderViewFrame *headerViewFrame = [self.commentDataArr[sender.tag] headerViewFrame];
    NSInteger topCommentId = headerViewFrame.commentModel.commentID;
    NSLog(@"---topCommentId = %ld", topCommentId);
    //获取子评论的ID(优先评论，每组 子评论的第 0 个评论)
    CommentCellFrame *cellFrame = [self.commentDataArr[sender.tag] cellFrameArr][0];
    NSInteger subCommentId = cellFrame.commentListModel.commentID;
    NSLog(@"***subCommentId = %ld",subCommentId);

    self.pageNum++;
    [self loadRequestWithSubCommentWithTopCommentId:topCommentId section:sender.tag subComentId:subCommentId currentPage:self.pageNum];
}

#pragma mark - didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击了第 %ld 组 第 %ld 行",indexPath.section, indexPath.row);
    //获取点击的这一行的用户名
    CommentCellFrame *cellFrame = [self.commentDataArr[indexPath.section] cellFrameArr][indexPath.row];
    CommentListModel *listModel = cellFrame.commentListModel;
    
    _cellIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
    NSLog(@"section - %ld - row - %ld",_cellIndexPath.section, _cellIndexPath.row);
    
    //用户名
    NSString *userName = listModel.userName;
    //让输入框成为第一响应者(弹出键盘)
    [self.commentTF becomeFirstResponder];

    if ([[self.commentTextDict objectForKey: _cellIndexPath] length] > 0) {
        self.commentTF.text = [self.commentTextDict objectForKey: _cellIndexPath];
    } else {
        self.commentTF.placeholder = [NSString stringWithFormat:@"回复 @%@", userName];
        self.commentTF.text = nil;
    }
    
    //获取点击的子评论的评论id
    NSInteger subCommentId = listModel.commentID;
    //调用新增评论的接口
//    [self.selectUserMdict setObject:@(topCommentId) forKey:@"topCommentId"];
    [self.selectUserMdict setObject:@(subCommentId) forKey:@"targetCommentId"];
    [self.selectUserMdict setObject:@(indexPath.section) forKey:@"selectSection"];
    [self.selectUserMdict setObject:@(indexPath.row) forKey:@"selectRow"];
    [self.selectUserMdict setObject:@(subCommentId) forKey:@"subCommentId"];
    [self.selectUserMdict setValue:@(2) forKey:@"isHeaderView"];
    
    NSLog(@"selectUserMdict = %@",self.selectUserMdict);
}

#pragma mark - tableView的长按手势
- (void)tableViewLongPress:(UILongPressGestureRecognizer *)longPressGesture {
    if (longPressGesture.state == UIGestureRecognizerStateBegan) { //手势开始
        CGPoint point = [longPressGesture locationInView:self.tableView];
        NSIndexPath *currentIndexPath = [self.tableView indexPathForRowAtPoint:point];
        NSLog(@"当前长按第 %ld组 第 %ld 行", currentIndexPath.section, currentIndexPath.row);
        //获取当前点击的那一行的评论文本
        CommentCellFrame *cellFrame = [self.commentDataArr[currentIndexPath.section] cellFrameArr][currentIndexPath.row];
        NSString *content = cellFrame.commentListModel.content;
        NSString *userName = cellFrame.commentListModel.userName;
        __weak typeof(self) weakSelf = self;
        [JZGTool showAlertWithVC:[JZGTool getCurrentVC] alertTitle:nil message:[NSString stringWithFormat:@"%@: %@", userName, content] actionTitle1:@"回复" actionTitle2:@"复制" actionTitle3:@"举报" actionTitle4:@"取消" handler:^(UIAlertAction *action) {
            NSLog(@" - %@",action);
            if ([action.title isEqualToString:@"回复"]) {
                NSLog(@"点击了回复按钮");
                //弹出键盘
                [self.commentTF becomeFirstResponder];
                weakSelf.cellIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row inSection:currentIndexPath.section];
                NSLog(@"headerView: 组 - %ld - 行 - %ld",weakSelf.cellIndexPath.section, weakSelf.cellIndexPath.row);
                
                if ([[weakSelf.commentTextDict objectForKey: weakSelf.cellIndexPath] length] > 0) {
                    weakSelf.commentTF.text = [weakSelf.commentTextDict objectForKey: weakSelf.cellIndexPath];
                } else {
                    //重置输入框的placeholder
                    weakSelf.commentTF.placeholder = [NSString stringWithFormat:@"回复 @%@", userName];
                    weakSelf.commentTF.text = nil;
                }
                //获取点击的子评论的评论id
                NSInteger subCommentId = cellFrame.commentListModel.commentID;
                //调用新增评论的接口
            //    [self.selectUserMdict setObject:@(topCommentId) forKey:@"topCommentId"];
                [self.selectUserMdict setObject:@(subCommentId) forKey:@"targetCommentId"];
                [self.selectUserMdict setObject:@(currentIndexPath.section) forKey:@"selectSection"];
                [self.selectUserMdict setObject:@(currentIndexPath.row) forKey:@"selectRow"];
                [self.selectUserMdict setObject:@(subCommentId) forKey:@"subCommentId"];
                [self.selectUserMdict setValue:@(2) forKey:@"isHeaderView"];
                
            } else if ([action.title isEqualToString:@"复制"]) {
                NSLog(@"点击了复制按钮");
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = content;
                [PRTools showProgressHUDWithText:@"已复制到剪切板" afterDelay:1];
            } else if ([action.title isEqualToString:@"举报"]) {
                NSLog(@"点击了举报按钮");
            }
        }];
    }
}

#pragma mark - 长按HeaderView手势事件
- (void)headerViewLongPress:(UILongPressGestureRecognizer *)longPressGesture {
    if (longPressGesture.state == UIGestureRecognizerStateBegan) { //手势开始
       // CGPoint point = [longPressGesture locationInView:self.tableView];
        //获取当前点击位置的indexPath
        //NSIndexPath *currentIndexPath = [self.tableView indexPathForRowAtPoint:point];
       // NSLog(@"长按HeaderView手势事件 - %ld - %ld",currentIndexPath.section, currentIndexPath.row);
        NSLog(@"---%ld ",longPressGesture.view.tag);
        //获取当前点击的这一组的用户名和评论文本
        CommentHeaderViewFrame *headerViewFrame = [self.commentDataArr[longPressGesture.view.tag] headerViewFrame];
        NSString *userName = headerViewFrame.commentModel.userName;
        NSString *content = headerViewFrame.commentModel.content;
        
        __weak typeof(self) weakSelf = self;
        [JZGTool showAlertWithVC:[JZGTool getCurrentVC] alertTitle:nil message:[NSString stringWithFormat:@"%@: %@", userName, content] actionTitle1:@"回复" actionTitle2:@"复制" actionTitle3:@"举报" actionTitle4:@"取消" handler:^(UIAlertAction *action) {
            NSLog(@" - %@",action);
            if ([action.title isEqualToString:@"回复"]) {
                NSLog(@"点击了回复按钮");
                //弹起输入框
                [self.commentTF becomeFirstResponder];
                weakSelf.cellIndexPath = [NSIndexPath indexPathForRow:-1 inSection:longPressGesture.view.tag];
                NSLog(@"headerView: 组 - %ld - 行 - %ld",weakSelf.cellIndexPath.section, weakSelf.cellIndexPath.row);
                
                if ([[weakSelf.commentTextDict objectForKey: weakSelf.cellIndexPath] length] > 0) {
                    weakSelf.commentTF.text = [weakSelf.commentTextDict objectForKey: weakSelf.cellIndexPath];
                } else {
                    //重置输入框的placeholder
                    weakSelf.commentTF.placeholder = [NSString stringWithFormat:@"回复 @%@", userName];
                    weakSelf.commentTF.text = nil;
                }
                NSInteger topCommentId = headerViewFrame.commentModel.commentID;
                [weakSelf.selectUserMdict setObject:@(longPressGesture.view.tag) forKey:@"headerViewTag"];
                [self.selectUserMdict setObject:@(topCommentId) forKey:@"headerViewTopCommentId"];
                [self.selectUserMdict setValue:@(1) forKey:@"isHeaderView"];
                
            } else if ([action.title isEqualToString:@"复制"]) {
                NSLog(@"点击了复制按钮");
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = content;
                [PRTools showProgressHUDWithText:@"已复制到剪切板" afterDelay:1];
            } else if ([action.title isEqualToString:@"举报"]) {
                NSLog(@"点击了举报按钮");
            }
        }];
    }
}

- (void)headerViewClickToReplyWithGestureRecognizer:(UIGestureRecognizer *)gesture {
    
}

#pragma mark - headerViewTap(headerView的点按手势)
- (void)headerViewTap:(UITapGestureRecognizer *)gesture {
    NSLog(@"点击了headerView - %@", gesture);
    NSLog(@"---gesture.view = %@",gesture.view);
    //获取当前点击的这个headerView的section
    NSLog(@"hederView的tag = %ld",gesture.view.tag);
    //获取当前点击的这一行的顶级评论id
    CommentHeaderViewFrame *headerFrame = [self.commentDataArr[gesture.view.tag] headerViewFrame];
    //获取点击的这一行的用户名
    NSString *userName = headerFrame.commentModel.userName;
    //弹出键盘
    [self.commentTF becomeFirstResponder];
    _cellIndexPath = [NSIndexPath indexPathForRow:-1 inSection:gesture.view.tag];
    NSLog(@"headerView: 组 - %ld - 行 - %ld",_cellIndexPath.section, _cellIndexPath.row);
    
    if ([[self.commentTextDict objectForKey: _cellIndexPath] length] > 0) {
        self.commentTF.text = [self.commentTextDict objectForKey: _cellIndexPath];
    } else {
        //重置输入框的placeholder
        self.commentTF.placeholder = [NSString stringWithFormat:@"回复 @%@", userName];
        self.commentTF.text = nil;
    }
    NSInteger topCommentId = headerFrame.commentModel.commentID;
    [self.selectUserMdict setObject:@(gesture.view.tag) forKey:@"headerViewTag"];
    [self.selectUserMdict setObject:@(topCommentId) forKey:@"headerViewTopCommentId"];
    [self.selectUserMdict setValue:@(1) forKey:@"isHeaderView"];
    
}

#pragma mark - UITextFieldDelegate
//-(void)textFieldDidBeginEditing:(UITextField *)textField {
//    // 当输入框获得焦点时，执行该方法 （光标出现时）。
//    //开始编辑时触发，文本字段将成为first responder
//    NSLog(@"textFieldDidBeginEditing - %@", textField.text);
//}

#pragma mark - 新增评论
- (void)loadRequestWithAddCommentNoteId:(NSInteger)noteId userId:(NSInteger)userId targetCommentId:(NSInteger)targetCommentId content:(NSString *)content section:(NSInteger)section row:(NSInteger)row {
    
    NSDictionary *paramDict = @{
        @"noteId": @(noteId),
        @"userId": @(userId),
        @"targetCommentId": @(targetCommentId),
        @"content": content
    };
    NSLog(@"新增 - paramDict = %@",paramDict);
    [[HttpRequest shareInstance]post:kNotesAddComment parameters:paramDict success:^(NSURLSessionDataTask * _Nonnull task, HttpResponseModel * _Nullable responseModel) {
        NSLog(@"新增评论responseModel = %@",responseModel);
        if (responseModel.code.integerValue == 0) {
            NSLog(@"评论新增成功");
            //获取 CommentListModel 类型的 data 数据
            CommentListModel *model = [CommentListModel yy_modelWithDictionary:responseModel.data];
            NSLog(@"新增 - model = %@",model);
            //获取新增的评论id
            [self.excludeCommentIdsmArr addObject: @(model.commentID)];
            NSLog(@"2----excludeCommentIdsmArr = %@",self.excludeCommentIdsmArr);

            if ([[self.selectUserMdict valueForKey:@"isHeaderView"] integerValue] == 1) {
                //如果此时点击的是headerView
                //创建新的模型数据
                CommentCellFrame *cellFrame = [[CommentCellFrame alloc]init];
                cellFrame.commentListModel = model;
                CommentDataModel *commentDataModel = [[CommentDataModel alloc]init];
                //获取当前点击的那一组那一行
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
                [[self.commentDataArr[section] cellFrameArr] insertObject:cellFrame atIndex:indexPath.row];
                commentDataModel.cellFrameArr = [self.commentDataArr[section] cellFrameArr];
            } else if ([[self.selectUserMdict valueForKey:@"isHeaderView"] integerValue] == 2) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
                //创建新的模型数据
                CommentCellFrame *cellFrame = [[CommentCellFrame alloc]init];
                cellFrame.commentListModel = model;
                CommentDataModel *commentDataModel = [[CommentDataModel alloc]init];
                [[self.commentDataArr[section] cellFrameArr] insertObject:cellFrame atIndex:indexPath.row + 1];
                commentDataModel.cellFrameArr = [self.commentDataArr[section] cellFrameArr];
            } else { //此时新增的是顶级评论
                //创建空的模型数据
                CommentHeaderViewFrame *headerViewFrame = [[CommentHeaderViewFrame alloc]init];
                headerViewFrame.commentModel = model;
                CommentDataModel *commenDatatModel = [[CommentDataModel alloc]init];
                commenDatatModel.headerViewFrame = headerViewFrame;
                //插入到第一个元素的位置
                [self.commentDataArr insertObject:commenDatatModel atIndex:0];
                NSLog(@"新增 - commentDataArr = %@ - count = %ld",self.commentDataArr, self.commentDataArr.count);
            }
            [self.tableView reloadData];
        }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"新增失败 - error = %@", error);
            [PRTools showProgressHUDWithError:@"加载失败..." afterDelay:1];
        }];
}


#pragma mark - 当点击键盘的返回键（右下角）时，执行该方法。(一般用来隐藏键盘)
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"textFieldShouldReturn - %@",textField.text);
    //新增评论

    //点击headerView
    if ([[self.selectUserMdict valueForKey:@"isHeaderView"] integerValue] == 1) {
        //获取当前点击的headerView的tag
        NSInteger headerViewTag = [[self.selectUserMdict valueForKey:@"headerViewTag"] integerValue];
        //获取当前点击的headerView的顶级评论Id
        NSInteger headerTopCommentId = [[self.selectUserMdict valueForKey:@"headerViewTopCommentId"] integerValue];
        [self loadRequestWithAddCommentNoteId:self.noteId userId:5565 targetCommentId:headerTopCommentId content:textField.text section:headerViewTag row:0];
    } else if ([[self.selectUserMdict valueForKey:@"isHeaderView"] integerValue] == 2) {
        //点击cell
        NSInteger targetCommentId = [[self.selectUserMdict valueForKey:@"targetCommentId"] integerValue];
        NSInteger selectSection = [[self.selectUserMdict valueForKey:@"selectSection"] integerValue];
        NSInteger selectRow = [[self.selectUserMdict valueForKey:@"selectRow"] integerValue];
        
        [self loadRequestWithAddCommentNoteId:self.noteId userId:5565 targetCommentId:targetCommentId content:textField.text section:selectSection row:selectRow];
    } else {
        [self loadRequestWithAddCommentNoteId:self.noteId userId:5565 targetCommentId:-1 content:textField.text section:0 row:0];
    }
    
    textField.text = nil;
    //隐藏键盘
    [self.commentTF resignFirstResponder];
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    //返回一个BOOL值，指定是否循序文本字段开始编辑
    NSLog(@"textFieldShouldBeginEditing - %@",textField.text);
    return YES;
}

#pragma mark - 开始编辑输入框（弹框开始弹出）
-(void)textFieldDidBeginEditing:(UITextField *)textField {
    self.commentTF.placeholder = @"喜欢就给个评论支持一下 ~";
    self.selectUserMdict = nil;
    _cellIndexPath = [NSIndexPath indexPathForRow:-1 inSection:-1];
    self.commentTF.text = nil;
    NSLog(@"textFieldDidBeginEditing - %@",textField.text);
}

-(void)textFieldDidChangeSelection:(UITextField *)textField {
    NSLog(@"textFieldDidChangeSelection - %@",textField.text);
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    //返回BOOL值，指定是否允许文本字段结束编辑，当编辑结束，文本字段会让出first responder
    //要想在用户结束编辑时阻止文本字段消失，可以返回NO
    //这对一些文本字段必须始终保持活跃状态的程序很有用，比如即时消息
    NSLog(@"textFieldShouldEndEditing - %@",textField.text);
    return YES;
}


-(void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"----text = %@ - commentTF = %@",textField.text,self.commentTF.text);
    
    [self.commentTextDict setObject:textField.text forKey:_cellIndexPath];
    NSLog(@"commentTextDict = %@",self.commentTextDict);
    
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{

//返回一个BOOL值指明是否允许根据用户请求清除内容
//可以设置在特定条件下才允许清除内容
    NSLog(@"textFieldShouldClear - %@",textField.text);
    return YES;
}


- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//当用户使用自动更正功能，把输入的文字修改为推荐的文字时，就会调用这个方法。
//这对于想要加入撤销选项的应用程序特别有用
//可以跟踪字段内所做的最后一次修改，也可以对所有编辑做日志记录,用作审计用途。
//要防止文字被改变可以返回NO
//这个方法的参数中有一个NSRange对象，指明了被改变文字的位置，建议修改的文本也在其中
//    NSLog(@"shouldChangeCharactersInRange - %@ - %ld - %ld - %@",textField.text, range.location, range.length, string);
//    NSLog(@"commentTF = %@,text = %@", self.commentTF.text,textField.text);
//    [self.commentTextDict setObject:self.commentTF.text forKey:_cellIndexPath];
//    NSLog(@"commentTextDict = %@",self.commentTextDict);
    
    //self.commentText = textField.text;
    //NSLog(@"commentTF = %@ - commentText = %@",self.commentTF.text, self.commentText);
    
    
    [self setNeedsUpdateConstraints];
    [self updateConstraints];
    if (string.length > 0) {
       // self.sendTextBtn.hidden = NO;
//        [self.commentTF mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(self.bottomAddCommentView).mas_offset(10);
//            make.left.mas_equalTo(self.bottomAddCommentView).mas_offset(10);
//            make.right.mas_equalTo(self.sendTextBtn.mas_left).mas_offset(-10);
//            make.height.mas_equalTo(36);
//        }];
//        [self.commentTF mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.right.mas_equalTo(self.sendTextBtn.mas_left).mas_offset(-10);
//            make.top.mas_equalTo(self.bottomAddCommentView).mas_offset(10);
//            make.left.mas_equalTo(self).mas_offset(10);
//            make.height.mas_equalTo(36);
//        }];
//        self.commentTF.frame = CGRectMake(10, 10, kSPScreenWidth - CGRectGetWidth(self.sendTextBtn.frame) - 5 - 10 - 10, 36);
    } else {
       // self.sendTextBtn.hidden = YES;
    }
    return YES;
}

//限制只能输入特定的字符

//-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    NSString* number= Knum;
//    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
//    return [numberPre evaluateWithObject:string];
//}
//上面那个Knum是一个宏，可以在文件顶部定义：

//#define Knum @"^[0-9]+$"
//听从queuey的意见把这个改成了正则表达式，正则表达式和谓词配合使用使代码精简易懂了不少，谢谢queuey的意见。(关于正则表达式和谓词的详细使用，我将会尽快整理出来供大家查阅) 所以，如果你要限制输入英文的话，就可以把这个定义为：

//#define Knum @"^[A-Za-z]+$"
//当然，你还可以在以上方法return之前，做一提示的，比如提示用户只能输入数字之类的。如果你觉得有需要的话。

//限制只能输入一定长度的字符

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
//{
//    //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
//
//    if ([string isEqualToString:@"n"])　//按会车可以改变
//    {
//        return YES;
//    }
//
//    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
//
//    if (self.myTextField == textField)　//判断是否时我们想要限定的那个输入框
//    {
//        if ([toBeString length] > 20)
//        {   //如果输入框内容大于20则弹出警告
//            textField.text = [toBeString substringToIndex:20];
//            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];
//            [alert show];
//            return NO;
//        }
//    }
//    return YES;
//}
//通知 UITextField派生自UIControl，所以UIControl类中的通知系统在文本字段中也可以使用。除了UIControl类的标准事件，你还可以使用下列UITextField类特有的事件

//UITextFieldTextDidBeginEditingNotification
//UITextFieldTextDidChangeNotification
//UITextFieldTextDidEndEditingNotification
////当文本字段退出编辑模式时触发。通知的object属性存储了最终文本。
////因为文本字段要使用键盘输入文字，所以下面这些事件发生时，也会发送动作通知
//
//UIKeyboardWillShowNotification 　//键盘显示之前发送
//UIKeyboardDidShowNotification  　//键盘显示之后发送
//UIKeyboardWillHideNotification 　//键盘隐藏之前发送
//UIKeyboardDidHideNotification  　//键盘隐藏之后发送
////UITextField 在storyboard 中设置属性











/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
